package com.lz.netty.consumer.project.netty;

import com.lz.netty.consumer.project.netty.config.ServerProperties;
import com.lz.netty.consumer.project.netty.util.MsgUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


/**
 * NettyClient启动
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class NettyClient {

    private final ServerProperties serverProperties;

    /**
     * 初始化启动netty客户端连接服务端
     */
    @PostConstruct
    public boolean start() {
        return connect(serverProperties.getHost(), serverProperties.getPort());
    }

    /**
     * netty客户端连接服务端
     */
    private boolean connect(String inetHost, int inetPort) {
        boolean isconnected = true;
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.AUTO_READ, true);
            b.handler(new MyChannelInitializer());
            ChannelFuture f = b.connect(inetHost, inetPort).sync();
            log.info("客户端开始连接");
            f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(), " 连接成功后，进行测试"));
            log.info("客户端连接成功");
            isconnected = true;
            //f.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("客户端连接异常：{}", e.getMessage());
            isconnected = false;
            //workerGroup.shutdownGracefully();
        } finally {
            log.info("客户端连接结束");
        }
        return isconnected;
    }
}
